#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
修复PyInstaller与Python 3.13的兼容性问题
解决distutils模块冲突的问题
"""

import os
import sys
import subprocess
import shutil

def fix_pyinstaller_distutils():
    """修复PyInstaller的distutils冲突问题"""
    print("正在修复PyInstaller的distutils冲突问题...")
    
    try:
        # 1. 卸载现有的PyInstaller
        print("1. 卸载现有的PyInstaller...")
        subprocess.run([sys.executable, "-m", "pip", "uninstall", "pyinstaller", "-y"], 
                      check=False, capture_output=True)
        
        # 2. 清理缓存
        print("2. 清理pip缓存...")
        subprocess.run([sys.executable, "-m", "pip", "cache", "purge"], 
                      check=False, capture_output=True)
        
        # 3. 安装特定版本的PyInstaller（兼容Python 3.13）
        print("3. 安装兼容的PyInstaller版本...")
        subprocess.run([sys.executable, "-m", "pip", "install", "pyinstaller==6.5.0"], 
                      check=True)
        
        # 4. 检查安装是否成功
        result = subprocess.run([sys.executable, "-c", "import PyInstaller; print(PyInstaller.__version__)"], 
                               capture_output=True, text=True)
        if result.returncode == 0:
            print(f"✅ PyInstaller安装成功，版本: {result.stdout.strip()}")
        else:
            print("❌ PyInstaller安装失败")
            return False
            
        return True
        
    except subprocess.CalledProcessError as e:
        print(f"❌ 修复过程中出现错误: {e}")
        return False

def clean_build_files():
    """清理构建文件"""
    print("清理旧的构建文件...")
    
    # 删除构建目录
    for folder in ['build', 'dist', '__pycache__']:
        if os.path.exists(folder):
            try:
                shutil.rmtree(folder)
                print(f"✅ 已删除: {folder}")
            except Exception as e:
                print(f"⚠️ 删除{folder}失败: {e}")
    
    # 删除spec文件（如果存在旧的）
    spec_files = [f for f in os.listdir('.') if f.endswith('.spec')]
    for spec_file in spec_files:
        try:
            os.remove(spec_file)
            print(f"✅ 已删除: {spec_file}")
        except Exception as e:
            print(f"⚠️ 删除{spec_file}失败: {e}")

def create_hook_file():
    """创建自定义hook文件来处理distutils问题"""
    hooks_dir = "hooks"
    if not os.path.exists(hooks_dir):
        os.makedirs(hooks_dir)
    
    hook_content = '''
# Custom hook to handle distutils conflicts
from PyInstaller.utils.hooks import collect_submodules

# 排除distutils相关模块
excludedimports = ['distutils', 'distutils.util', 'setuptools.distutils']

# 收集必要的隐藏导入
hiddenimports = []

# 处理可能的别名问题
def hook(hook_api):
    """自定义hook处理函数"""
    pass
'''
    
    hook_file = os.path.join(hooks_dir, "hook-distutils.py")
    with open(hook_file, 'w', encoding='utf-8') as f:
        f.write(hook_content)
    
    print(f"✅ 已创建自定义hook文件: {hook_file}")
    return hooks_dir

def main():
    """主函数"""
    print("=" * 50)
    print("PyInstaller兼容性修复工具")
    print("=" * 50)
    
    # 1. 修复PyInstaller
    if not fix_pyinstaller_distutils():
        print("❌ PyInstaller修复失败，请手动处理")
        return False
    
    # 2. 清理构建文件
    clean_build_files()
    
    # 3. 创建自定义hook
    hooks_dir = create_hook_file()
    
    # 4. 更新spec文件中的hookspath
    spec_file = "成帧数据应用软件.spec"
    if os.path.exists(spec_file):
        with open(spec_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 更新hookspath
        content = content.replace("hookspath=[],", f"hookspath=['{hooks_dir}'],")
        
        with open(spec_file, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"✅ 已更新spec文件的hookspath")
    
    print("\n✅ 修复完成！现在可以尝试重新打包软件。")
    print("建议使用以下命令进行打包:")
    print("python -m PyInstaller 成帧数据应用软件.spec")
    
    return True

if __name__ == "__main__":
    main() 